import { computePosition, flip, shift } from '@floating-ui/dom'
import { posToDOMRect, VueRenderer } from '@tiptap/vue-3'
import type { Editor } from '@tiptap/core'

import MentionList from './index.vue'

interface UpdatePositionParams {
  editor: Editor
  element: HTMLElement
}

const updatePosition = ({ editor, element }: UpdatePositionParams): void => {
  const virtualElement = {
    getBoundingClientRect: () => posToDOMRect(editor.view, editor.state.selection.from, editor.state.selection.to),
  }

  computePosition(virtualElement, element, {
    placement: 'bottom-start',
    strategy: 'absolute',
    middleware: [shift(), flip()],
  }).then(({ x, y, strategy }) => {
    element.style.width = 'max-content'
    element.style.position = strategy
    element.style.left = `${x}px`
    element.style.top = `${y}px`
  })
}

// 全局变量来跟踪当前活动的组件
let currentComponent: VueRenderer | null = null

const suggestion = {
  items: ({ query }: { query: string; editor: Editor }) => {
    // 这个函数现在会被 Tiptap 组件中的 customSuggestion 覆盖
    // 保留默认实现以防万一
    const items = [

    ]
    
    return items
      .filter(item => item.toLowerCase().includes(query.toLowerCase()))
  },

  render: () => {
    let component: VueRenderer

    return {
      onStart: (props: any) => {
        // 清理之前的组件
        if (currentComponent && currentComponent.element) {
          try {
            currentComponent.destroy()
            currentComponent.element.remove()
          } catch (error) {
            console.warn('Cleanup previous component error:', error)
          }
        }

        // 清理可能存在的其他下拉菜单
        const existingMenus = document.querySelectorAll('.dropdown-menu')
        existingMenus.forEach(el => el.remove())

        component = new VueRenderer(MentionList as any, {
          props,
          editor: props.editor,
        })

        currentComponent = component

        if (!props.clientRect || !component.element) {
          return
        }

        ;(component.element as HTMLElement).style.position = 'absolute'

        document.body.appendChild(component.element)

        updatePosition({ editor: props.editor, element: component.element as HTMLElement })
      },

      onUpdate(props: any) {
        if (component && component.ref) {
          component.updateProps(props)
        }

        if (!props.clientRect || !component.element) {
          return
        }

        updatePosition({ editor: props.editor, element: component.element as HTMLElement })
      },

      onKeyDown(props: any): boolean {
        if (props.event.key === 'Escape') {
          if (component && component.element) {
            component.destroy()
            component.element.remove()
            currentComponent = null
          }

          return true
        }

        return component?.ref?.onKeyDown(props) || false
      },

      onExit() {
        if (component && component.element) {
          component.destroy()
          component.element.remove()
          currentComponent = null
        }
      },
    }
  },
}

// 添加热更新处理
if (import.meta.hot) {
  import.meta.hot.accept(() => {
    // 热更新时清理当前组件
    if (currentComponent && currentComponent.element) {
      try {
        currentComponent.destroy()
        currentComponent.element.remove()
        currentComponent = null
      } catch (error) {
        console.warn('Hot reload cleanup error:', error)
      }
    }
    
    // 清理所有可能残留的下拉菜单
    const existingMenus = document.querySelectorAll('.dropdown-menu')
    existingMenus.forEach(el => el.remove())
  })
}

export default suggestion